<template>
  <ul class="text">
    <div class="tabs">
      <div class="tab" :class="{ 'on': currentType == 0 }" @click="handletab(0)">私有组件</div>
      <div class="tab" :class="{ 'on': currentType == 1 }" @click="handletab(1)">公开组件</div>
    </div>

    <li @mouseover="getCurrentCustomId(item, index)" v-contextmenu="contextmenusThumbnails"
      v-for="(item, index) in cList" :key="index" :class="{ 'outline': dragIndex === index }"
      :style="{ marginLeft: index % 2 != 0 ? '10px' : '18px' }">
      <div class="custom" draggable="true" @dragstart="dragstart(index)"
        @dragend="dragCustom($event, item.compContent)">
        <Custom :slide="item.compContent" :size="100" :customScale="item.customScale" />
      </div>
      <p>{{ item.compName }}</p>
      <dd class="mask"></dd>
    </li>
    <dd class="nodata" v-if="cList.length === 0">还没有自定义组件，快去添加吧！</dd>
    <Modal v-model:visible="renameVisible" :footer="null" centered :width="400" destroyOnClose>
      <div class="model">
        <div class="model-title">修改组件名称</div>
        <div class="flex1">
          <Input v-model:value="rename" :class="{ 'customNameTest': customNameTest }" @change="customNameTest = false"
            showCount :maxlength="10" placeholder="请输入组件名称" />
          <Button @click="updateCustom()" :class="{ 'customBtnTest': !rename }">修改</Button>
          <!-- <a-radio-group v-model:value="customType">
            <a-radio :value="0">
              私有组件
            </a-radio>
            <a-radio :value="1">
              公开组件
            </a-radio>
          </a-radio-group> -->
        </div>
      </div>
    </Modal>

  </ul>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue'
// import { customList } from '@/mocks/custom'
import Custom from '@/views/components/ThumbnailSlide/custom.vue'
import { getElementListRange } from '@/utils/element'
import { storeToRefs } from 'pinia'
import { ContextmenuItem } from '@/components/Contextmenu/types'

import { useMainStore } from '@/store'
// import request from '@/utils/request'
import { getCustomTempaleList ,deleteCustomTempaleList,getUserInfoCustom,changeCustomTempaleList,editCustomTempaleList} from "@/api/custom_template";
import { message } from 'ant-design-vue'
import emitter, { EmitterEvents } from '@/utils/emitter'

export default defineComponent({
  name: 'custom-pool',
  emits: ['select'],
  components: {
    Custom
  },
  setup(props, { emit }) {
    const { canvasScale, customList } = storeToRefs(useMainStore())
    const renameVisible = ref(false)
    const rename = ref()
    const customNameTest = ref(false)
    const cList = ref([])
    const currentType = ref(0)
    const customScale = ref(1)
    const customDataList = () => {
      cList.value.map((item: any, index: any, arr: any) => {
        item.compContent = JSON.parse(item.compContent)
        const { minX, maxX, minY, maxY } = getElementListRange(item.compContent)
        const width = computed(() => (maxX - minX))
        const height = computed(() => (maxY - minY))
        let left = item.compContent.reduce((init: any, j: any) => {
          return Math.min(init, j.left)
        }, Infinity)
        let top = item.compContent.reduce((init: any, j: any) => {
          return Math.min(init, j.top)
        }, Infinity)
        // console.log(width.value, height.value, 'height')
        if (width.value > 1000) {
          arr[index].customScale = 1000 / width.value
        }
        if (height.value > 1000) {
          arr[index].customScale = 1000 / height.value
        }
        return item.compContent.map((self: any) => {
          self.left = self.left - left + 500 - (width.value / 2)
          self.top = self.top - top + 500 - (height.value / 2)
          // return self
        })
      })
      // console.log(cList.value, ' cList.value')

    }
    const dragIndex = ref()
    const dragstart = (index: number) => {
      // console.log(index, 'sstart')
      dragIndex.value = index
    }
    const dragCustom = ($event: MouseEvent, custom: any) => {
      // $event.preventDefault()
      emit('select', { custom, $event })
      dragIndex.value = undefined
    }
    const handletab = (type: number) => {
      currentType.value = type
      getList()
    }
    const userInfo = ref()
    const getUserInfo = () => {
      // hhxsUserId
      getUserInfoCustom().then((res:any) => {
        if (res.data.code === 200) {
          userInfo.value = res.data.data
        }
      })
      // request.get(`/api/sc/user/get/user/info`).then(res => {
      //   if (res.data.code === 200) {
      //     userInfo.value = res.data.data
      //   }
      // })
    }
    const getList = () => {
      getCustomTempaleList({
        compType: currentType.value,
        current: 1,
        size: 10
      }).then((res:any) => {
        if (res.data.code === 200) {
          cList.value = res.data.data.list
          customDataList()
          // useMainStore().setCustomList(cList.value)
          // console.log(cList,'customDataListcustomDataList')
        }
      })
      // request.post(`/hhxs-app/app/ssc/comp/list`, {
      //   compType: currentType.value,
      //   current: 1,
      //   size: 10
      // }).then(res => {
      //   if (res.data.code === 200) {
      //     cList.value = res.data.data.list
      //     customDataList()
      //     // useMainStore().setCustomList(cList.value)
      //     // console.log(cList,'customDataListcustomDataList')
      //   }
      // })
    }
    const contextmenusThumbnails = (): ContextmenuItem[] => {
      let arr: ContextmenuItem[] = []
      if (currentType.value === 0) {
        arr = [
           {
            text: '公开组件',
            subText: '',
            handler: () => updateCustom(1),
          },
          {
            text: '重命名',
            subText: '',
            handler: () => {
              renameVisible.value = true
              rename.value = currentName.value
            }
          },
          {
            text: '删除',
            subText: '',
            handler: deleteCustom,
          },
          
         
        ]
      }
      if (currentType.value === 1) {
        // console.log(userInfo.value.hhxsUserId, currentID.value.insertedBy, 'currentID.value.insertedBy')

        if (userInfo.value.hhxsUserId === currentID.value.insertedBy) {
          arr = [
            {
              text: '删除组件',
              subText: '',
              handler: deleteCustom,
            },
            {
              text: '添加到私有',
              subText: '',
              handler: () => updateCustom(0),
            },
          ]
        } else {
          arr = [
            {
              text: '添加到私有',
              subText: '',
              handler: () => updateCustom(0),
            },
          ]
        }
      }
      return arr
    }

    const currentID = ref()
    const currentIndex = ref()
    const currentName = ref()
    const getCurrentCustomId = (item: any, index: any) => {
      currentIndex.value = index
      currentID.value = item
      currentName.value = item.compName

    }

    const deleteCustom = () => {
      deleteCustomTempaleList({id:currentID.value.compId}).then((res:any) => {
        if (res.data.code === 200) {
          cList.value.splice(currentIndex.value, 1)
          message.success('删除成功')
        }
      })
      // console.log('deleteCustom', currentID.value)
      // request.get(`/hhxs-app/app/ssc/comp/del/${currentID.value.compId}`).then(res => {
      //   if (res.data.code === 200) {
      //     cList.value.splice(currentIndex.value, 1)
      //     message.success('删除成功')
      //   }
      // })
    }
    const updateCustom = (type: any) => {  //type =1 公共组件 =0 私有 =2 重命名
    
      if (type === 1 || type === 0) { //改为公共组件type =1 公共组件 =0 私有
        changeCustomTempaleList({
          compContent: JSON.stringify(currentID.value.compContent),
          compName: currentID.value.compName,
          compId: currentID.value.compId,
          compType: type
        }).then((res:any) => {  
          if (res.data.code === 200) {
            message.success('成功！')
          }else if(res.data.code===406){
            message.success('请勿重复提交！')
          }else {
            message.success(res.data.msg)
          }
        }).catch(err => {
          message.success(err.data.msg)
        })
        // request.post(`/hhxs-app/app/ssc/comp/sharePrivateMutualRotation`, {
        //   compContent: JSON.stringify(currentID.value.compContent),
        //   compName: currentID.value.compName,
        //   compId: currentID.value.compId,
        //   compType: type
        // }).then(res => {
        //   if (res.data.code === 200) {
        //     message.success('成功！')
        //   }else if(res.data.code===406){
        //     message.success('请勿重复提交！')
        //   }else {
        //     message.success(res.data.msg)
        //   }
        // })
      } else {  //重命名
      if (!rename.value) {
          customNameTest.value = true
          return
        }

        let obj = {
          compId: currentID.value.compId,
          compName: rename.value,
          compType: currentID.value.compType
        }
        editCustomTempaleList(obj).then((res:any) => {
          if (res.data.code === 200) {
            message.success('修改成功')
            renameVisible.value = false
            rename.value = ''
            getList()
          }
        })
        // request.post(`/hhxs-app/app/ssc/comp/update`, obj).then(res => {
        //   if (res.data.code === 200) {
        //     message.success('修改成功')
        //     renameVisible.value = false
        //     rename.value = ''
        //     getList()
        //   }
        // })
      }

    }
    onMounted(() => {
      getList()
      getUserInfo()
      emitter.on(EmitterEvents.GET_CUSTOM_LIST, getList)
    })
    onUnmounted(() => {
      emitter.off(EmitterEvents.GET_CUSTOM_LIST, getList)
    })
    return {
      customDataList,
      dragCustom,
      getList,
      contextmenusThumbnails,
      updateCustom,
      deleteCustom,
      getCurrentCustomId,
      currentID,
      currentIndex,
      currentName,
      cList,
      renameVisible,
      rename,
      customNameTest,
      currentType,
      handletab,
      getUserInfo,
      userInfo,
      dragstart,
      dragIndex,
      customScale,
    }
  },
})
</script>

<style lang="scss" scoped>
::v-deep(.chart-content) {
  width: 100px !important;
  height: 100px !important;
}

.nodata {
  color: #626377;
  text-align: center;
  padding: 50px 0;
  clear: both;
}

.model {
  .flex1 {
    position: relative;

    .ant-radio-group {
      margin-top: 20px;
    }
  }

  h3 {
    font-weight: 600;
    font-size: 16px;
    margin-bottom: 15px;
  }

  p {
    color: #959fba;
    font-size: 14px;
    line-height: 14px;
    margin: 15px 0;
  }

  input {
    height: 46px;
    background: #f0f1f3;
    border-radius: 10px;
    border: 1px solid rgba(240, 241, 243, 1);
  }

 .customNameTest {
    border: 1px solid red;
  }

  .customBtnTest {
    opacity: 0.5;
  }

  button {
    position: absolute;
    right: 0;
    height: 46px;
    width: 80px;
    border-radius: 10px;
    background: #686ce8;

    &:hover,
    &:active,
    &:focus {
      background: #7a7ef0 !important;
      color: #fff;
    }
  }
}

.tabs {
  display: flex;
  margin-bottom: 17px;
  // border-bottom: 1px solid $contentBorderColor;

  .tab {
    flex: 1;
    text-align: center;
    color: #fff;
    line-height: 40px;
    font-size: 18px;
    cursor: pointer;

    &::after {
      position: absolute;
      display: block;
      content: '';
      width: 16px;
      height: 3px;
      background: #a6a9ff;
      border-radius: 2px;
      bottom: 0;
      left: 50%;
      margin-left: -8px;
      opacity: 0;
      transform: translateX(50px);
      transition: .2s transform cubic-bezier(0.38, 0.8, 0.32, 1.07);
    }

    &:nth-child(2)::after {
      transform: translateX(-50px);
    }

    &.on {
      color: #a6a9ff;
      position: relative;

      &::after {
        opacity: 1;
        transform: translateX(0);
      }
    }
  }
}

.custom {
  border: 1px dashed #afacc7;
  overflow: hidden;
}

ul.text {
  overflow: hidden;

  li {
    float: left;
    width: 122px;
    height: 147px;
    margin-bottom: 10px;
    background: #fff;
    padding: 18px 10px 0;
    border-radius: 8px;
    position: relative;

    p {
      text-align: center;
      padding: 5px 0 10px 0;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .icon {
      width: 100%;
      height: 74px;
    }

    .mask {
      position: absolute;
      display: none;
      content: '';
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(104, 108, 232, 0.2);
    }

    &:hover {
      cursor: move;

      &.mask {
        display: block;
      }
    }
  }
}

.model-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #4B4D54;
  letter-spacing: 0;
  line-height: 16px;
  font-weight: 400;
}

</style>
